import {
    reqGetShopCartList,
    reqDeleteGood,
    reqSwitchStatus
} from '@/api'


export const state = {
    shopCartList: []
}

export const mutations = {
    GETSHOPCARTLIST(state, shopCartList) {
        state.shopCartList = shopCartList
    }
}

export const actions = {
    //发请求获取购物车列表
    async getShopCartList({commit}) {
        let result = await reqGetShopCartList();
        if (result.code == 200) {
            commit('GETSHOPCARTLIST', result.data)
        }
    },
    // 发起删除商品的请求
    async deleteGoods({commit}, skuId) {
        let result = await reqDeleteGood(skuId)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 修改商品的选中状态
    async switchStatus({commit}, {skuId,isChecked}) {
        let result = await reqSwitchStatus(skuId, isChecked)
        if (result.code == 200) {
            return 'ok'
        } else {
            return Promise.reject(new Error('faile'))
        }
    },
    // 删除选中的所有商品
    deleteAllChecked({dispatch,getters}){
        let promiseAll = [];
        getters.shopCartList.cartInfoList.forEach((item)=>{
            if(item.isChecked == 1){
               let promise =  dispatch('deleteGoods',item.skuId)
               promiseAll.push(promise)
            }
        })
        // 如果所有的promise都成功，返回的结果为成功，如果有一个不成功，返回的结果就为失败
      return  Promise.all(promiseAll)
    },
    // 全部产品的勾选状态的修改
    allChecked({dispatch,getters},isChecked){
        let promiseAll = []
        getters.shopCartList.cartInfoList.forEach((item)=>{
            if(item.isChecked !== isChecked){
                let promise = dispatch('switchStatus',{skuId:item.skuId,isChecked:isChecked})
                promiseAll.push(promise)
            }
        })

        return Promise.all(promiseAll)
    }
}

export const getters = {
    shopCartList(state) {
        return state.shopCartList[0] || {}
    }
}

export default {
    state,
    mutations,
    actions,
    getters
}